import React, { useState, useEffect, useMemo } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Typography,
  Space,
  Tag,
  Tooltip,
  Select,
  Button,
  Alert
} from 'antd';
import {
  BarChartOutlined,
  ReloadOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';

const { Title, Text } = Typography;
const { Option } = Select;

/**
 * 双色球开奖记录分布图组件
 * 显示红球和蓝球的出现频率分布
 */
const LotteryDistribution = ({ historyData = [], isMobile = false }) => {
  const [chartType, setChartType] = useState('bar'); // bar, pie, line
  const [period, setPeriod] = useState('all'); // all, recent30, recent60, recent90

  // 过滤数据根据时间段
  const filteredData = useMemo(() => {
    if (period === 'all') return historyData;
    
    const now = new Date();
    const days = parseInt(period.replace('recent', ''));
    const cutoffDate = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
    
    return historyData.filter(record => {
      const recordDate = new Date(record.opendatetime || record.opendate || record.createTime);
      return recordDate >= cutoffDate;
    });
  }, [historyData, period]);

  // 计算红球分布数据
  const redBallDistribution = useMemo(() => {
    const distribution = {};
    
    // 初始化1-33号球的计数
    for (let i = 1; i <= 33; i++) {
      distribution[i] = 0;
    }
    
    // 统计每个号码的出现次数
    filteredData.forEach(record => {
      if (record.number) {
        const redBalls = record.number.split(' ').map(num => parseInt(num));
        redBalls.forEach(ball => {
          if (ball >= 1 && ball <= 33) {
            distribution[ball]++;
          }
        });
      }
    });
    
    return distribution;
  }, [filteredData]);

  // 计算蓝球分布数据
  const blueBallDistribution = useMemo(() => {
    const distribution = {};
    
    // 初始化1-16号球的计数
    for (let i = 1; i <= 16; i++) {
      distribution[i] = 0;
    }
    
    // 统计每个号码的出现次数
    filteredData.forEach(record => {
      if (record.refernumber) {
        const blueBall = parseInt(record.refernumber);
        if (blueBall >= 1 && blueBall <= 16) {
          distribution[blueBall]++;
        }
      }
    });
    
    return distribution;
  }, [filteredData]);

  // 获取最大出现次数（用于计算百分比）
  const maxRedCount = Math.max(...Object.values(redBallDistribution));
  const maxBlueCount = Math.max(...Object.values(blueBallDistribution));
  const totalRecords = filteredData.length;

  // 获取热门号码（出现次数最多的前5个）
  const getHotNumbers = (distribution, count = 5) => {
    return Object.entries(distribution)
      .sort(([,a], [,b]) => b - a)
      .slice(0, count)
      .map(([num, freq]) => ({ number: parseInt(num), frequency: freq }));
  };

  // 获取冷门号码（出现次数最少的前5个）
  const getColdNumbers = (distribution, count = 5) => {
    return Object.entries(distribution)
      .sort(([,a], [,b]) => a - b)
      .slice(0, count)
      .map(([num, freq]) => ({ number: parseInt(num), frequency: freq }));
  };

  const hotRedNumbers = getHotNumbers(redBallDistribution);
  const coldRedNumbers = getColdNumbers(redBallDistribution);
  const hotBlueNumbers = getHotNumbers(blueBallDistribution);
  const coldBlueNumbers = getColdNumbers(blueBallDistribution);

  // 渲染号码分布条形图
  const renderBarChart = (distribution, maxCount, color, title) => {
    return (
      <Card 
        title={title} 
        size={isMobile ? 'small' : 'default'}
        style={{ marginBottom: 16 }}
      >
        <div style={{ 
          display: 'grid', 
          gridTemplateColumns: isMobile ? 'repeat(6, 1fr)' : 'repeat(11, 1fr)',
          gap: isMobile ? '4px' : '8px',
          padding: '8px 0'
        }}>
          {Object.entries(distribution).map(([number, count]) => {
            const percentage = maxCount > 0 ? (count / maxCount) * 100 : 0;
            const frequency = totalRecords > 0 ? ((count / totalRecords) * 100).toFixed(1) : '0.0';
            
            return (
              <Tooltip 
                key={number}
                title={`号码 ${number}: 出现 ${count} 次 (${frequency}%)`}
              >
                <div style={{ 
                  textAlign: 'center',
                  cursor: 'pointer'
                }}>
                  <div style={{
                    height: isMobile ? '40px' : '60px',
                    display: 'flex',
                    alignItems: 'flex-end',
                    justifyContent: 'center',
                    marginBottom: '4px'
                  }}>
                    <div style={{
                      width: isMobile ? '20px' : '30px',
                      height: `${Math.max(percentage, 2)}%`,
                      backgroundColor: color,
                      borderRadius: '2px 2px 0 0',
                      minHeight: '2px',
                      opacity: percentage > 0 ? 1 : 0.3
                    }} />
                  </div>
                  <Text style={{ 
                    fontSize: isMobile ? '10px' : '12px',
                    fontWeight: count === maxCount ? 'bold' : 'normal',
                    color: count === maxCount ? color : undefined
                  }}>
                    {number}
                  </Text>
                  <div style={{ fontSize: isMobile ? '8px' : '10px', color: '#666' }}>
                    {count}
                  </div>
                </div>
              </Tooltip>
            );
          })}
        </div>
      </Card>
    );
  };

  // 渲染统计信息
  const renderStatistics = () => {
    return (
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col span={isMobile ? 12 : 6}>
          <Statistic
            title="分析期数"
            value={totalRecords}
            suffix="期"
            valueStyle={{ fontSize: isMobile ? '16px' : '20px' }}
          />
        </Col>
        <Col span={isMobile ? 12 : 6}>
          <Statistic
            title="红球总数"
            value={totalRecords * 6}
            suffix="个"
            valueStyle={{ fontSize: isMobile ? '16px' : '20px' }}
          />
        </Col>
        <Col span={isMobile ? 12 : 6}>
          <Statistic
            title="蓝球总数"
            value={totalRecords}
            suffix="个"
            valueStyle={{ fontSize: isMobile ? '16px' : '20px' }}
          />
        </Col>
        <Col span={isMobile ? 12 : 6}>
          <Statistic
            title="平均频率"
            value={totalRecords > 0 ? (totalRecords * 6 / 33).toFixed(1) : '0.0'}
            suffix="次/号"
            valueStyle={{ fontSize: isMobile ? '16px' : '20px' }}
          />
        </Col>
      </Row>
    );
  };

  // 渲染热门冷门号码
  const renderHotColdNumbers = () => {
    return (
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col span={isMobile ? 24 : 12}>
          <Card title="热门红球" size={isMobile ? 'small' : 'default'}>
            <Space wrap>
              {hotRedNumbers.map(({ number, frequency }) => (
                <Tag key={number} color="red" style={{ margin: '2px' }}>
                  {number} ({frequency}次)
                </Tag>
              ))}
            </Space>
          </Card>
        </Col>
        <Col span={isMobile ? 24 : 12}>
          <Card title="冷门红球" size={isMobile ? 'small' : 'default'}>
            <Space wrap>
              {coldRedNumbers.map(({ number, frequency }) => (
                <Tag key={number} color="blue" style={{ margin: '2px' }}>
                  {number} ({frequency}次)
                </Tag>
              ))}
            </Space>
          </Card>
        </Col>
        <Col span={isMobile ? 24 : 12}>
          <Card title="热门蓝球" size={isMobile ? 'small' : 'default'}>
            <Space wrap>
              {hotBlueNumbers.map(({ number, frequency }) => (
                <Tag key={number} color="red" style={{ margin: '2px' }}>
                  {number} ({frequency}次)
                </Tag>
              ))}
            </Space>
          </Card>
        </Col>
        <Col span={isMobile ? 24 : 12}>
          <Card title="冷门蓝球" size={isMobile ? 'small' : 'default'}>
            <Space wrap>
              {coldBlueNumbers.map(({ number, frequency }) => (
                <Tag key={number} color="blue" style={{ margin: '2px' }}>
                  {number} ({frequency}次)
                </Tag>
              ))}
            </Space>
          </Card>
        </Col>
      </Row>
    );
  };

  if (!historyData || historyData.length === 0) {
    return (
      <Card>
        <Alert
          message="暂无数据"
          description="请先同步开奖历史记录，然后查看分布图"
          type="info"
          showIcon
          icon={<InfoCircleOutlined />}
        />
      </Card>
    );
  }

  return (
    <div style={{ padding: isMobile ? '8px' : '16px' }}>
      {/* 标题和控制面板 */}
      <Card style={{ marginBottom: 16 }}>
        <Row justify="space-between" align="middle" gutter={[16, 16]}>
          <Col>
            <Title level={isMobile ? 4 : 3} style={{ margin: 0 }}>
              <BarChartOutlined style={{ marginRight: 8 }} />
              号码分布图
            </Title>
          </Col>
          <Col>
            <Space wrap>
              <Select
                value={period}
                onChange={setPeriod}
                style={{ width: isMobile ? 100 : 120 }}
                size={isMobile ? 'small' : 'middle'}
              >
                <Option value="all">全部</Option>
                <Option value="recent30">近30期</Option>
                <Option value="recent60">近60期</Option>
                <Option value="recent90">近90期</Option>
              </Select>
              <Button
                icon={<ReloadOutlined />}
                size={isMobile ? 'small' : 'middle'}
                onClick={() => {
                  // 触发重新计算
                  setPeriod(period);
                }}
              >
                刷新
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 统计信息 */}
      {renderStatistics()}

      {/* 分布图 */}
      {renderBarChart(redBallDistribution, maxRedCount, '#ff4d4f', '红球分布 (1-33)')}
      {renderBarChart(blueBallDistribution, maxBlueCount, '#1890ff', '蓝球分布 (1-16)')}

      {/* 热门冷门号码 */}
      {renderHotColdNumbers()}

      {/* 说明信息 */}
      <Card size={isMobile ? 'small' : 'default'}>
        <Alert
          message="分布图说明"
          description={
            <div>
              <p>• 柱状图高度表示号码出现的相对频率</p>
              <p>• 数字下方显示具体出现次数</p>
              <p>• 热门号码：出现频率较高的号码</p>
              <p>• 冷门号码：出现频率较低的号码</p>
              <p>• 可通过时间段筛选查看不同周期的分布情况</p>
            </div>
          }
          type="info"
          showIcon
        />
      </Card>
    </div>
  );
};

export default LotteryDistribution;